import { defineStore } from 'pinia'
import { asyncRoutes } from '@/router'
import type { RouteRecordRaw } from 'vue-router'

export const usePermissionStore = defineStore('permission', {
  state: () => ({
    routes: [] as RouteRecordRaw[],
    addRoutes: [] as RouteRecordRaw[]
  }),
  actions: {
    generateRoutes(roles: string[]): Promise<RouteRecordRaw[]> {
      return new Promise(resolve => {
        let accessedRoutes: RouteRecordRaw[] = []
        
        // 管理员拥有所有权限
        if (roles.includes('admin')) {
          accessedRoutes = asyncRoutes
        } else {
          // 过滤异步路由
          accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
        }
        
        this.addRoutes = accessedRoutes
        this.routes = [...accessedRoutes]
        resolve(accessedRoutes)
      })
    }
  }
})

// 递归过滤路由
function filterAsyncRoutes(routes: RouteRecordRaw[], roles: string[]): RouteRecordRaw[] {
  const res: RouteRecordRaw[] = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

// 验证路由权限
function hasPermission(roles: string[], route: RouteRecordRaw): boolean {
  const routeRoles = route.meta?.roles
  // 没有设置roles表示无需权限
  if (!routeRoles) return true
  return roles.some(role => routeRoles.includes(role))
}